/**
 * 
 */
package com.rhf.ui.admin.beans;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.taglibs.display.TableDecorator;

import com.rhf.core.commons.logging.AppLog;
import com.rhf.core.commons.logging.AppLogManager;
import com.rhf.ui.Utils;
import com.rhf.ui.admin.session.UserSession;
import com.rhf.ui.admin.session.UserSessionKey;

/**
 * @author fabiensaulnier
 * 
 */
public class BaseBean extends TableDecorator {

	/**
	 * The application logger
	 */
	protected AppLog appLog;

	/**
	 * the base path
	 */
	protected String basePath;

	/**
	 * user session
	 */
	protected UserSession userSession;

	/**
	 * Message d'information
	 */
	protected String message;

	/**
	 * 
	 */
	public BaseBean() {
		this.appLog = AppLogManager.getUiLogger();
	}

	/**
	 * Actions effectu�es par d�faut au chargement d'une page :<br/>
	 * - R�cup�ration du chemin de l'application<br/>
	 * - R�cup�ration de la session utilisateur
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void onLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// D�finition du chemin
		String path = request.getContextPath();
		basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

		// R�cup�ration de la session utilisateur
		this.userSession = (UserSession) request.getSession().getAttribute(UserSessionKey.USER_SESSION);

	}

	/**
	 * V�rifie les param�tres obligatoires
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void checkMandatoryParameter(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// V�rification si la session existe
		if (this.userSession == null) {
			appLog.warn("No found UserSession in http request");
			throw new Exception("Vous n'�tes pas connect�, veuillez vous identifier.");
		}

	}

	/**
	 * @param request
	 * @param response
	 * @param tab
	 * @param redirect
	 * @throws Exception
	 */
	public void endAction(HttpServletRequest request, HttpServletResponse response, String redirect, String optionalRedirectParameter)
			throws Exception {

		// update the current user session
		request.getSession().setAttribute(UserSessionKey.USER_SESSION, this.userSession);
		String path = redirect + Utils.stringValue(optionalRedirectParameter);
		appLog.debug("Redirect URL to [" + path + "]");
		response.sendRedirect(path);
	}

	/**
	 * @return the basePath
	 */
	public String getBasePath() {
		return basePath;
	}

	/**
	 * @return the userSession
	 */
	public UserSession getUserSession() {
		return this.userSession;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return this.message;
	}

}
